package com.sky.controller.admin;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.sky.constant.UploadConstant;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Path;

/**
 * @Author: Yosoo
 * @Date: 2025/5/17 09:22
 * @Description:
 */
@RestController
@Api(tags = "通用接口")
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public Result<String> upload(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return Result.error("上传文件为空");
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = FileNameUtil.getSuffix(originalFilename);
        String newName = IdUtil.randomUUID()  + "." + suffix;
        Path uploadPath = Path.of(UploadConstant.UPLOAD_PATH, newName);
        try {
            // 确保目录存在
            java.io.File directory = new java.io.File(UploadConstant.UPLOAD_PATH);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            file.transferTo(uploadPath);
        } catch (IOException e) {
            log.error("上传文件失败: {}", e.getMessage(), e);
            return Result.error("文件上传失败: " + e.getMessage());
        }
        return Result.success(UploadConstant.UPLOAD_URL+newName);
    }
}
